package com.tydic.portal.controller;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tydic.borderer.domain.AgentContract;
import com.tydic.borderer.domain.BorderAgent;
import com.tydic.borderer.domain.BordererInfo;
import com.tydic.borderer.mapper.AgentContractMapper;
import com.tydic.borderer.mapper.BorderAgentMapper;
import com.tydic.borderer.mapper.BordererInfoMapper;
import com.tydic.borderer.service.IAgentContractService;
import com.tydic.borderer.service.IBorderAgentService;
import com.tydic.borderer.service.IBordererInfoService;
import com.tydic.common.core.domain.R;
import com.tydic.common.core.enums.*;
import com.tydic.common.core.exception.api.ApiException;
import com.tydic.common.core.utils.DateUtils;
import com.tydic.common.redis.constant.RedisKey;
import com.tydic.common.redis.utils.RedisUtils;
import com.tydic.enterprise.domain.Enterprise;
import com.tydic.enterprise.domain.EnterpriseUser;
import com.tydic.enterprise.mapper.EnterpriseMapper;
import com.tydic.enterprise.service.IEnterpriseService;
import com.tydic.enterprise.service.IEnterpriseUserService;
import com.tydic.order.domain.Order;
import com.tydic.order.domain.OrderContract;
import com.tydic.order.enums.OrderStatus;
import com.tydic.order.mapper.OrderContractMapper;
import com.tydic.order.mapper.OrderMapper;
import com.tydic.order.service.IOrderContractService;
import com.tydic.order.service.IOrderService;
import com.tydic.product.domain.Product;
import com.tydic.product.mapper.ProductMapper;
import com.tydic.product.service.IProductService;
import com.tydic.system.domain.*;
import com.tydic.system.domain.req.SendSmsRequest;
import com.tydic.system.mapper.SysUserMapper;
import com.tydic.system.service.IFddService;
import com.tydic.system.service.ISysMessageService;
import com.tydic.system.service.ISysUserService;
import com.tydic.system.utils.SmsUtils;
import com.tydic.workflow.service.IPurchaseOrderService;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.runtime.ProcessInstance;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.Duration;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@RestController
@RequiredArgsConstructor
@RequestMapping(value = "/fdd")
@Slf4j

public class FddController {

    private final IBordererInfoService bordererInfoService;
    private final IPurchaseOrderService purchaseOrderService;
    private final IProductService productService;
    private final IFddService fddService;
    private final IEnterpriseService enterpriseService;
    private final IEnterpriseUserService enterpriseUserService;
    private final ISysUserService userService;
    private final IOrderContractService orderContractService;
    private final IOrderService orderService;
    private final IAgentContractService agentContractService;
    private final IBorderAgentService borderAgentService;
    private final SysUserMapper userMapper;
    private final BordererInfoMapper bordererInfoMapper;
    private final OrderContractMapper orderContractMapper;
    private final OrderMapper orderMapper;
    private final BorderAgentMapper borderAgentMapper;
    private final EnterpriseMapper enterpriseMapper;
    private final AgentContractMapper agentContractMapper;
    private final ISysMessageService messageService;
    private final ProductMapper productMapper;
    /**
     * 法大大个人实名认证回调
     *
     * @param verifyAccountCallback
     * @return
     */
    /**
     * 法大大个人实名认证回调
     */
    @PostMapping("/verifyAccount")
    public R verifyAccount(@RequestBody VerifyAccountCallback verifyAccountCallback) {
        Account account = fddService.getAccountById(verifyAccountCallback.getAccountId());
        if (account == null) {
            return R.fail("更新用户状态异常");
        }
        SysUser user = userService.getUserByLoginCode(account.getMobile());
        boolean success = false;
        if (user != null) {
            String userCertificationStatus;
            if (StrUtil.equalsAny(verifyAccountCallback.getStatus(), UserCertificationStatusCallbckEnum.SUCCESS.getStatus(), UserCertificationStatusCallbckEnum.CHANGE_SUCCESS.getStatus(), UserCertificationStatusCallbckEnum.CHANGE_FAIL.getStatus())) {
                userCertificationStatus = UserCertificationStatusEnum.SUCCESS.getStatus();
            } else if (StrUtil.equals(verifyAccountCallback.getStatus(), UserCertificationStatusCallbckEnum.READY.getStatus())) {
                userCertificationStatus = UserCertificationStatusEnum.READY.getStatus();
            } else if (StrUtil.equals(verifyAccountCallback.getStatus(), UserCertificationStatusCallbckEnum.CERTIFICATING.getStatus())) {
                userCertificationStatus = UserCertificationStatusEnum.CERTIFICATING.getStatus();
            } else {
                userCertificationStatus = UserCertificationStatusCallbckEnum.FAIL.getStatus();
            }
            if (StrUtil.equals(user.getUserType(), UserTypeEnum.BORDERER.getUserType())) {
                BordererInfo bordererInfo = bordererInfoService.getBordererInfoByUserCode(user.getUserCode());
                if (bordererInfo != null) {
                    bordererInfo.setUserCertificationStatus(userCertificationStatus);
                    bordererInfoMapper.updateById(bordererInfo);
                    success = true;
                }
            } else if (StrUtil.equalsAny(user.getUserType(), UserTypeEnum.ENTERPRISE.getUserType(), UserTypeEnum.EMPLOYEE.getUserType())) {
                Enterprise enterprise = enterpriseService.getEnterpriseByUserCode(user.getUserCode());
                if (enterprise != null) {
                    enterprise.setUserCertificationStatus(userCertificationStatus);
                }
                EnterpriseUser enterpriseUser = enterpriseUserService.findByUserCode(user.getUserCode());
                if (enterpriseUser != null) {
                    enterpriseUser.setCertificationStatus(userCertificationStatus);
                    enterpriseUserService.update(enterpriseUser);
                    success = true;
                }
            }
        }
        return success ? R.okCallBack("更新用户状态成功") : R.fail("更新用户状态异常");
    }

    @PostMapping("/verifyEnterprise")
    public R verifyEnterprise(@RequestBody VerifyEnterpriseCallback verifyEnterpriseCallback) {
        Company company = fddService.getCompanyByCompanyId(verifyEnterpriseCallback.getCompanyId());
        if (company == null) {
            return R.fail("更新企业状态异常");
        }
        Account account = fddService.getAccountById(company.getLegalAccountId());
        if (account == null) {
            return R.fail("法人账号不存在");
        }
        SysUser user = userService.getUserByLoginCode(account.getMobile());
        boolean success = false;
        if (user != null) {
            String enterpriseCertificationStatus;
            if (StrUtil.equalsAny(verifyEnterpriseCallback.getStatus(), EnterpriseCertificationStatusCallbckEnum.SUCCESS.getStatus(), EnterpriseCertificationStatusCallbckEnum.CHANGE_SUCCESS.getStatus(), EnterpriseCertificationStatusCallbckEnum.CHANGE_FAIL.getStatus())) {
                enterpriseCertificationStatus = EnterpriseCertificationStatusEnum.SUCCESS.getStatus();
            } else if (StrUtil.equals(verifyEnterpriseCallback.getStatus(), EnterpriseCertificationStatusCallbckEnum.READY.getStatus())) {
                enterpriseCertificationStatus = EnterpriseCertificationStatusEnum.READY.getStatus();
            } else if (StrUtil.equals(verifyEnterpriseCallback.getStatus(), EnterpriseCertificationStatusCallbckEnum.CERTIFICATING.getStatus())) {
                enterpriseCertificationStatus = EnterpriseCertificationStatusEnum.CERTIFICATING.getStatus();
            } else {
                enterpriseCertificationStatus = EnterpriseCertificationStatusEnum.FAIL.getStatus();
            }
            if (StrUtil.equals(user.getUserType(), UserTypeEnum.BORDERER.getUserType())) {
                BordererInfo bordererInfo = bordererInfoService.getBordererInfoByUserCode(user.getUserCode());
                if (bordererInfo != null) {
                    bordererInfo.setEnterpriseCertificationStatus(enterpriseCertificationStatus);
                    bordererInfoService.update(bordererInfo);
                    success = true;
                }
            } else if (StrUtil.equalsAny(user.getUserType(), UserTypeEnum.ENTERPRISE.getUserType())) {
                Enterprise enterprise = enterpriseService.getEnterpriseByUserCode(user.getUserCode());
                if (enterprise != null) {
                    enterprise.setEnterpriseCertificationStatus(enterpriseCertificationStatus);
                }
            }
        }
        return success ? R.okCallBack("更新企业状态成功") : R.fail("更新企业状态异常");
    }

    /**
     * 签署回调 [2023年11月21日 增加子订单处理逻辑]
     *
     * @param createAndPushCallBack
     * @return
     */
    /**
     * 签署回调
     */
    @PostMapping("/updateSignStatus")
    @Transactional(rollbackFor = Exception.class)
    public R updateSignStatus(@RequestBody CreateAndPushCallBack createAndPushCallBack) {

        log.info("签署回调请求对象：---- " + JSON.toJSONString(createAndPushCallBack));

        if (ObjectUtil.isEmpty(createAndPushCallBack) || CollUtil.isEmpty(createAndPushCallBack.getSignList())) {
            throw new ApiException("更新签署状态异常,请求参数为空");
        }

        log.info("签署回调请求对象：---- " + JSON.toJSONString(createAndPushCallBack));

        //根据docId和合同ID 查询当前合同在我们平台是否存在
        List<OrderContract> orderContractList = orderContractService.getByDocId(createAndPushCallBack.getDocId());
        if (CollUtil.isEmpty(orderContractList)) {
            return R.fail("更新签署状态异常");
        }
        OrderContract orderContractResult = orderContractList.get(0);
        Order order = orderMapper.selectById(orderContractResult.getOrderId());


        if (ObjectUtil.isEmpty(order)) {
            return R.fail("更新签署状态异常");
        }

        if (!StrUtil.equals(order.getOrderStatus(), OrderStatus.WAIT_SIGN.getStatus())) {
            log.error("当前合同未在待签署状态");
            return R.fail("当前合同未在待签署状态");
        }

        List<Sign> signList = createAndPushCallBack.getSignList();

        //根据文档状态判断 是否为已拒绝
        if (createAndPushCallBack.getContractStatus() == 5) {
            //已拒绝，更新订单状态为已取消
            order.setOrderStatus(OrderStatus.CANCEL.getStatus());
            order.setBordererSign(SignStatusEum.UNSIGNED.getStatus());
            order.setCompanySign(SignStatusEum.UNSIGNED.getStatus());

            orderContractResult.setBordererSign(SignStatusEum.REFUSE.getStatus());
            orderContractResult.setCompanySign(SignStatusEum.REFUSE.getStatus());
            orderContractResult.setSignStatus(SignStatusEum.REFUSE.getStatus());

            orderMapper.updateById(order);
            orderContractMapper.updateById(orderContractResult);
            // 更新商品状态
            updateProductStatus(order.getProductId(), ProductSaleStatus.SALE);

            // 同步父订单状态，和更新子商品状态
            updateParent(order, ProductSaleStatus.SALE);

            return R.okCallBack("更新签署状态成功");
        }


        //根据签署ID手机号，签署人ID、签署在人我方的ID，判断是边民，还是企业，进而更新状态

        for (Sign sign : signList) {
            if (sign.getNotifyNo() != null) {
                if (orderContractResult.getBordererSignNotify() != null && sign.getNotifyNo().equals(orderContractResult.getBordererSignNotify())) {
                    /**
                     * 边民身份
                     */
                    if (sign.getSignStatus() != null && Objects.equals(sign.getSignStatus(), 0)) {
                        orderContractResult.setBordererSign(SignStatusEum.SIGNED.getStatus());
                        order.setBordererSign(SignStatusEum.SIGNED.getStatus());
                        RedisUtils.decrAtomicValue(RedisKey.BORDERER_SIGN_CONTRACT.createRedisKey(order.getParentOrderId()));
                    }
                    if (sign.getSignTime() != null) {
                        orderContractResult.setBordererSignDate(DateUtils.parseDate(sign.getSignTime()));
                        order.setBordererSignDate(DateUtils.parseDate(sign.getSignTime()));
                    }

                } else if ((orderContractResult.getCompanySignNotify() != null && sign.getNotifyNo().equals(orderContractResult.getCompanySignNotify()))) {
                    /**
                     * 企业身份
                     */
                    if (sign.getSignStatus() != null) {
                        if (Objects.equals(sign.getSignStatus(), 0)) {
                            orderContractResult.setCompanySign(SignStatusEum.SIGNED.getStatus());
                            order.setCompanySign(SignStatusEum.SIGNED.getStatus());
                            RedisUtils.decrAtomicValue(RedisKey.ENTERPRISE_SIGN_CONTRACT.createRedisKey(order.getParentOrderId()));

                        }
                    }
                    if (sign.getSignTime() != null) {
                        orderContractResult.setCompanySignDate(DateUtils.parseDate(sign.getSignTime()));
                        order.setCompanySignDate(DateUtils.parseDate(sign.getSignTime()));
                    }
                }
            }

        }


        if (createAndPushCallBack.getDownloadUrl() != null) {
            orderContractResult.setDownloadUrl(createAndPushCallBack.getDownloadUrl());
        }
        orderContractResult.setUpdateBy("法大大回调");
        orderContractResult.setUpdateDate(new Date());
        if (createAndPushCallBack.getRefuseReason() != null) {
            orderContractResult.setRefuseReason(createAndPushCallBack.getRefuseReason());
        }

        if (orderContractResult.getBordererSign().equals(SignStatusEum.SIGNED.getStatus()) && orderContractResult.getCompanySign().equals(SignStatusEum.SIGNED.getStatus())) {
            order.setOrderStatus(OrderStatus.WAIT_PAY.getStatus());
        }

        orderContractMapper.updateById(orderContractResult);

        orderMapper.updateById(order);

        updateProductStatus(order.getProductId(), ProductSaleStatus.SOLD);

        // 同步父订单状态，和更新父商品状态
        updateParent(order, ProductSaleStatus.SOLD);

        return R.okCallBack("更新签署状态成功");
    }


    /**
     * 获取短信token
     */
    @GetMapping("/getSmsToken")
    public R getSmsToken(@NotBlank(message = "手机号码不能为空") @RequestParam("mobile") String mobile) {
        String redisKey = RedisKey.SMS_TOKEN.createRedisKey(mobile);
        String token = IdUtil.randomUUID();
        RedisUtils.setCacheObject(redisKey, token, Duration.ofMinutes(1L));
        return R.ok("成功", token);
    }

    /**
     * 发送短信
     */
    @PostMapping("/sendSms")
    public R sendSms(@Valid @RequestBody SendSmsRequest sendSmsRequest) {
        String redisKey = RedisKey.SMS_TOKEN.createRedisKey(sendSmsRequest.getMobile());
        String token = RedisUtils.getCacheObject(redisKey);
        if (StrUtil.isBlank(token) || !StrUtil.equals(token, sendSmsRequest.getSmsToken())) {
            return R.fail("发送短信失败");
        }
        RedisUtils.deleteObject(redisKey);
        SmsUtils.sendSms(sendSmsRequest.getMobile(), sendSmsRequest.getMessage());
        return R.ok("发送短信成功");
    }

    /**
     * 签署回调
     */
    @PostMapping("/updateAgentSignStatus")
    @Transactional(rollbackFor = Exception.class)
    public R updateAgentSignStatus(@RequestBody CreateAndPushCallBack createAndPushCallBack) {

        log.info("签署回调请求对象：---- " + JSON.toJSONString(createAndPushCallBack));

        if (ObjectUtil.isEmpty(createAndPushCallBack) || CollUtil.isEmpty(createAndPushCallBack.getSignList())) {
            throw new ApiException("更新签署状态异常,请求参数为空");
        }
        log.info("签署回调请求对象：---- " + JSON.toJSONString(createAndPushCallBack));

        //根据docId和合同ID 查询当前合同在我们平台是否存在
        AgentContract agentContract = new AgentContract();
        agentContract.setDocId(createAndPushCallBack.getDocId());
        List<AgentContract> orderContractList = agentContractService.getByDocId(agentContract.getDocId());
        if (CollUtil.isEmpty(orderContractList)) {
            return R.fail("更新签署状态异常");
        }
        AgentContract agentContractResult = orderContractList.get(0);
        if (agentContractResult.getSignStatus().equals(SignStatusEum.SIGNED.getStatus())) {
            log.error("当前合同未在待签署状态");
            return R.fail("当前合同未在待签署状态");
        }
        BorderAgent borderAgent = borderAgentService.findById(agentContractResult.getAgentId());
        if (ObjectUtil.isEmpty(borderAgent)) {
            return R.fail("更新签署状态异常");
        }
        List<Sign> signList = createAndPushCallBack.getSignList();
        //根据文档状态判断 是否为已拒绝
        if (createAndPushCallBack.getContractStatus() == 5) {
            //已拒绝，更新订单状态为已取消
            //TODO  如果只有两个人，则两个人的状态都要更新
            List<BorderAgent> list = borderAgentMapper.selectList(new LambdaQueryWrapper<BorderAgent>()
                .eq(BorderAgent::getAgentBordererId, borderAgent.getAgentBordererId()));
            if (CollUtil.isNotEmpty(list) && list.size() == 2) {
                for (BorderAgent agent : list) {
                    agent.setApplyStatus(AgentApplyStatusEnum.FAIL.getStatus());
                    borderAgentMapper.updateById(agent);
                }
            } else {
                borderAgent.setApplyStatus(AgentApplyStatusEnum.FAIL.getStatus());
                borderAgentMapper.updateById(borderAgent);
            }
            agentContract.setFirstPartySign(SignStatusEum.REFUSE.getStatus());
            agentContract.setSecondPartySign(SignStatusEum.REFUSE.getStatus());
            agentContract.setSignStatus(SignStatusEum.REFUSE.getStatus());
            agentContractMapper.updateById(agentContract);
            return R.okCallBack("更新签署状态成功");
        }


        //根据签署ID手机号，签署人ID、签署在人我方的ID，判断是边民，还是企业，进而更新状态

        for (Sign sign : signList) {
            if (sign.getNotifyNo() != null) {
                //说明是委托方
                if (agentContractResult.getFirstPartySignNotify() != null && sign.getNotifyNo().equals(agentContractResult.getFirstPartySignNotify())) {
                    /**
                     * 委托方身份
                     */
                    if (sign.getSignStatus() != null && Objects.equals(sign.getSignStatus(), 0)) {
                        agentContractResult.setFirstPartySign(SignStatusEum.SIGNED.getStatus());
                        BordererInfo agentBorderer = bordererInfoService.getBordererInfoById(borderAgent.getAgentBordererId());
                        messageService.insertMessageHandler(MessageCategoryEnum.AGENT,
                            borderAgent.getId(), "邀请授权委托代理",
                            borderAgent.getBordererName() + "邀请" + borderAgent.getAgentBordererName() + "成为受委托人", agentBorderer.getUserCode());
                    }
                    if (sign.getSignTime() != null) {
                        agentContractResult.setFirstPartySignDate(DateUtils.parseDate(sign.getSignTime()));
                    }
                } else if ((agentContractResult.getSecondPartySignNotify() != null && sign.getNotifyNo().equals(agentContractResult.getSecondPartySignNotify()))) {
                    /**
                     * 受委托方身份
                     */
                    if (sign.getSignStatus() != null) {
                        if (Objects.equals(sign.getSignStatus(), 0)) {
                            //根据规定了签署顺序，受邀方一定是后签署
                            agentContractResult.setSecondPartySign(SignStatusEum.SIGNED.getStatus());
                            if (agentContractResult.getFirstPartySign().equals(SignStatusEum.SIGNED.getStatus())
                                && agentContractResult.getSecondPartySign().equals(SignStatusEum.SIGNED.getStatus())) {
                                //总签署状态
                                agentContractResult.setSignStatus(SignStatusEum.SIGNED.getStatus());
                                borderAgent.setApplyContractStatus(SignStatusEum.SIGNED.getStatus());
                                borderAgent.setApplyStatus(AgentApplyStatusEnum.AGREE.getStatus());
                                borderAgentService.invalidPreviousBorderAgent(borderAgent.getId());
                                BordererInfo bordererInfoById = bordererInfoService.getBordererInfoById(borderAgent.getAgentBordererId());
                                userService.updateUserType(UserTypeEnum.BORDERER_AGENT.getUserType(), bordererInfoById.getUserCode());
                                messageService.completeMessage(MessageCategoryEnum.AGENT, agentContractResult.getAgentId(), bordererInfoById.getUserCode());
                            }
                        }
                    }
                    if (sign.getSignTime() != null) {
                        agentContractResult.setSecondPartySignDate(DateUtils.parseDate(sign.getSignTime()));
                    }
                }
            }
        }

        if (createAndPushCallBack.getDownloadUrl() != null) {
            agentContractResult.setDownloadUrl(createAndPushCallBack.getDownloadUrl());
        }
        agentContractResult.setUpdateBy("法大大回调");
        agentContractResult.setUpdateDate(new Date());
        if (createAndPushCallBack.getRefuseReason() != null) {
            agentContractResult.setRefuseReason(createAndPushCallBack.getRefuseReason());
        }
        agentContractMapper.updateById(agentContractResult);
        borderAgent.setUpdateBy("法大大回调");
        borderAgentMapper.updateById(borderAgent);
        // 边民代表更新状态之后设置消息完成
        if (SignStatusEum.SIGNED.equalsStatus(agentContractResult.getSecondPartySign())) {
            String userCode = bordererInfoService.getBordererInfoById(borderAgent.getAgentBordererId()).getUserCode();
            messageService.completeMessage(MessageCategoryEnum.AGENT, borderAgent.getId(), userCode);
        }

        return R.okCallBack("更新签署状态成功");
    }

    /**
     * 开通或关闭免验证签服务回调
     */
    @PostMapping("/openUnwantedAuthSignCallback")
    public R openUnwantedAuthSignCallback(@RequestBody OpenUnwantedAuthSignCallback callback) {

        //更新用户免验证签状态，如果是免验证签则直接更新边民/企业状态
        if (ObjectUtil.isEmpty(callback)) {
            return R.fail("免验证失败");
        }
        //根据授权主题类型判断开通人身份 1（边民）2（企业）
        if (NumberUtil.equals(callback.getAuthorizerFlag(), AuthTypeEnum.BORDERER.getType())) {
            Account account = fddService.getAccountById(callback.getAuthorizerTargetId());
            BordererInfo bordererInfo = bordererInfoService.getBordererInfoByPhoneNumber(account.getMobile());
            if (callback.getStatus() == 1) {
                bordererInfo.setOpenAuthSignStatus(EnableEnum.ENABLE.getStatus());
            } else {
                bordererInfo.setOpenAuthSignStatus(EnableEnum.DISABLE.getStatus());
            }
            bordererInfoService.update(bordererInfo);
        } else if (NumberUtil.equals(callback.getAuthorizerFlag(), AuthTypeEnum.ENTERPRISE.getType())) {
            Enterprise entity = enterpriseService.getByEnterpriseCode(callback.getAuthorizerTargetId());
            if (callback.getStatus() == 1) {
                entity.setOpenAuthSignStatus(EnableEnum.ENABLE.getStatus());
            } else {
                entity.setOpenAuthSignStatus(EnableEnum.DISABLE.getStatus());
            }
            enterpriseMapper.updateById(entity);
        }
        return R.ok();
    }

    //委托协议回调法大大回调

    private void updateParent(Order childOrder, ProductSaleStatus productSaleStatus) {

        int borderSignNum = (int) RedisUtils.getAtomicValue(RedisKey.BORDERER_SIGN_CONTRACT.createRedisKey(childOrder.getParentOrderId()));
        int companySignNum = (int) RedisUtils.getAtomicValue(RedisKey.ENTERPRISE_SIGN_CONTRACT.createRedisKey(childOrder.getParentOrderId()));
        //当所有子订单都是已支付的状态，就可以将父订单设置为已支付
        //查询总订单信息
        Order entity = orderMapper.selectById(childOrder.getParentOrderId());
        //企业签订状态
        if (companySignNum <= 0 && !StrUtil.equals(entity.getCompanySign(), SignStatusEum.SIGNED.getStatus())) {
            entity.setCompanySign(SignStatusEum.SIGNED.getStatus());
            entity.setCompanySignDate(new Date());
            RedisUtils.deleteObject(RedisKey.ENTERPRISE_SIGN_CONTRACT.createRedisKey(childOrder.getParentOrderId()));
            Enterprise enterprise = enterpriseMapper.selectById(entity.getEnterpriseId());
            messageService.completeMessage(MessageCategoryEnum.ENTERPRISE_SIGN, entity.getId(), enterprise.getUserCode());
            //通知边民签署合同
            sendBorderMessage(entity);
        }
        //边民签订状态
        if (borderSignNum <= 0 && !StrUtil.equals(entity.getBordererSign(), SignStatusEum.SIGNED.getStatus())) {
            entity.setBordererSign(SignStatusEum.SIGNED.getStatus());
            entity.setBordererSignDate(new Date());
            RedisUtils.deleteObject(RedisKey.BORDERER_SIGN_CONTRACT.createRedisKey(childOrder.getParentOrderId()));
            BordererInfo bordererInfo = bordererInfoService.getBordererInfoById(entity.getBorderAgentId());
            messageService.completeMessage(MessageCategoryEnum.BORDER_SIGN, entity.getId(), bordererInfo.getUserCode());
        }

        if (borderSignNum <= 0 && companySignNum <= 0) {
            entity.setOrderStatus(OrderStatus.WAIT_PAY.getStatus());
            Enterprise enterprise = enterpriseMapper.selectById(entity.getEnterpriseId());
            SysUser user = userMapper.selectById(enterprise.getUserCode());
            ProcessInstance processInstance = purchaseOrderService.startProcess(entity.getId(), user.getUserCode(), user.getLoginCode());
            entity.setProcInstId(processInstance.getProcessInstanceId());
            RedisUtils.setCacheObject(RedisKey.PAY_ORDER.createRedisKey(entity.getId()), entity.getId(), Duration.ofMinutes(30L));
            orderMapper.updateById(entity);
            messageService.insertMessageHandler(MessageCategoryEnum.WAIT_PAY, entity.getId(), "订单待付款", String.format("订单%s已完成合同签署，请在30分钟内完成付款", entity.getId()), enterprise.getUserCode());
        } else {
            orderMapper.updateById(entity);
        }
        /*orderService.findList(selectChildren).forEach(item -> {
            // 更新子订单状态
            item.setOrderStatus(paren.getOrderStatus());
            item.setBordererSign(paren.getBordererSign());
            item.setCompanySign(paren.getCompanySign());

            item.setBordererSignDate(paren.getBordererSignDate());
            item.setCompanySignDate(paren.getCompanySignDate());
            orderMapper.updateById(item);
            // 更新子商品状态
            updateProductStatus(item.getProductId(), productSaleStatus);
        });*/
    }

    private void updateProductStatus(String productId, ProductSaleStatus status) {
        Product product = productService.get(productId);
        if (ObjectUtil.isNotNull(product)) {
            product.setSale(status.getStatus());
            productMapper.updateById(product);
        }

        List<Product> list = productService.findByParentProductId(product.getParentProductId());
        int i = 0;
        for (Product item : list) {
            if (item.getSale().equals("3")) {
                i++;
            }
        }
        //当所有子产品都是已出售的状态，就可以将父产品设置为已出售
        if (list.size() == i) {
            Product entity = productMapper.selectById(product.getParentProductId());
            entity.setSale("3");
            productMapper.updateById(entity);
        }

        // 签约成功，删除缓存任务
//        RedisUtils.deleteObject(RedisKey.PLACE_ORDER_CACHE.createRedisKey(productId));
    }

    private void sendBorderMessage(Order order) {
        BordererInfo bordererInfo = bordererInfoService.getBordererInfoById(order.getBorderAgentId());
        messageService.insertMessage(MessageCategoryEnum.BORDER_SIGN, order.getId(), "新的订单待签署", "订单编号:" + order.getId() + "待签署", bordererInfo.getUserCode());
    }

}
